package cn.com.callback
import groovy.json.*

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory
import cn.com.elite.EliteBean;
import cn.com.elite.Util;

public class apiDealFileSync implements ServiceBackInvoke{
	private static final Log log=LogFactory.getLog(apiDealFileSync.class);
	public String doCallBack(EliteBean eliteBean,HttpServletRequest request,HttpServletResponse response) {
		
		response.setCharacterEncoding("UTF-8");
		log.debug("start apiDealFileSync...");

		//定义参数
		String callJson="";
		String jssPath = "/ngs/jss";
		String apiPath = "/EliteGeneralHttpTask/GeneralService/apiDealFileSync";
		String reJson = "";

		InputStreamReader reader = new InputStreamReader(request.getInputStream(),"utf-8");
		BufferedReader iny = new BufferedReader(reader);
		String line;
		while ((line = iny.readLine()) != null) {
			callJson += line;
		}
		
		log.debug("接收报文callJson:" + callJson);

		try {
			def getBody=new JsonSlurper().parseText(callJson);

			def type = getBody.type;
			def source = getBody.source;
			def target = getBody.target;


			if(type == '1'){
				List<String> dealList = new ArrayList<>();

				int tolNum = 0;
				int succNum = 0;
				//循环检查服务器是否存在这个文件，有则跳出循环
				def webServerUrlList = eliteBean.chaxun_sql("select replace(WebServerURL,'"+jssPath+"','"+apiPath+"') as WebServerURL from webserverlist",'dataSource');

				tolNum = webServerUrlList.size();
				log.debug("查询数据库配置服务器地址数量:" + tolNum);

				for(int i = 0; i < webServerUrlList.size; i++) {
					def webServerUrl =webServerUrlList.get(i).get("WebServerURL");

					//通知集群中主机缓存数据
					String sendBody = "{\"type\":\"0\",\"source\":\"" + source + "\",\"target\":\"" + target + "\"}";
					log.debug("调用参数信息:" +" callUrl:" +webServerUrl +" callBady:" + sendBody);

					//调用通知其他集群主机
					//def httpResult = HttpClient.sendPost(webServerUrl, sendBody);
					def httpResult = Util.doHttpPost(webServerUrl, sendBody, "UTF-8",10000, 0);
					log.debug("调用短信接口返回信息:" + httpResult);

					def root = new JsonSlurper().parseText(httpResult);
					def code = root.code;
					def message = root.message;
					if(code == "1") {
						succNum = succNum + 1;
					}
					dealList.add("{\"code\":\""+code+"\",\"url\":\""+webServerUrl+"\",\"message\":\""+message+"\"}");

				}
				reJson = "{\"code\":\"1\",\"tolnum\":\""+tolNum+"\",\"sucnum\":\""+succNum+"\",\"message\":\"缓存文件处理完成\",\"value\":"+dealList.toString()+"}";

			}
			else {
				//处理文件
				File sourcePath = new File(source);
				File targetPath = new File(target);

				if (!sourcePath.exists()) {
					log.debug("原始文件不存在：" +source);
					reJson = "{\"code\":\"-1\",\"message\":\"原始文件不存在\"}";
				}else {
					// 检查目标文件是否存在，不存在则创建
					if (targetPath.exists()) {
						log.debug("目标文件已经存在:" + target);
						reJson = "{\"code\":\"1\",\"message\":\"目标文件已经存在\"}";
					}else {
						boolean dealResult = copyFile(source, target, true);
						log.debug("复制文件处理结果:" + dealResult);
						if(dealResult == true) {
							reJson = "{\"code\":\"1\",\"message\":\"目标文件已经存在\"}";
						}else {
							reJson = "{\"code\":\"-1\",\"message\":\"复制文件失败\"}";

						}
						dealResult=Util.deleteFile(source);
					    log.debug("原文件delete处理结果:" + dealResult);
					}
				}
			}
		}catch (Exception e) {

			log.error("CheckHtmlFileResponse接口调用异常,异常信息：", e);
			reJson= "{\"code\":\"0\",\"message\":\"异常信息:"+e.getMessage()+"\",\"value\":[]}";
		}
		return reJson;

	}

	public static boolean copyFile(String srcFileName, String destFileName, boolean overlay)
	{
		File srcFile = new File(srcFileName);

		if (!srcFile.exists()) {
			log.error("源文件：" + srcFileName + "不存在!");
			return false;
		}
		if (!srcFile.isFile()) {
			log.error("复制文件失败，源文件：" + srcFileName + "不是一个文件！");
			return false;
		}

		File destFile = new File(destFileName);
		if (destFile.exists())
		{
			if (overlay)
			{
				new File(destFileName).delete();
			}

		}
		else if (!destFile.getParentFile().exists())
		{
			if (!destFile.getParentFile().mkdirs())
			{
				return false;
			}

		}

		int byteread = 0;
		InputStream inp = null;
		OutputStream out = null;
		try {
			inp = new FileInputStream(srcFile);
			out = new FileOutputStream(destFile);
			byte[] buffer = new byte[1024];
			while ((byteread = inp.read(buffer)) != -1) {
				out.write(buffer, 0, byteread);
			}
			return true;
		} catch (Exception e) {
			log.error(e);
			return false;
		} finally {
			try {
				if (out != null) {
					out.close();
				}
				if (inp != null)
					inp.close();
			}
			catch (IOException e) {
				log.error(e);
			}
		}
	}

}



